/**
 * Copyright (C) 2010 Zhang, Guilin <guilin.zhang@hotmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.ministock.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.http4j.Client;
import com.google.code.http4j.impl.BasicClient;
import com.google.code.ministock.ServiceProvider;
import com.google.code.ministock.Stock;

/**
 * <a href="http://hq.sinajs.cn/list=sh601006,sz300005,sz000001">Example URL</a>
 * @author <a href="mailto:guilin.zhang@hotmail.com">Zhang, Guilin</a>
 */
public class SinaServiceProvider implements ServiceProvider {
	
	private static final String RESTFUL_URL = "http://hq.sinajs.cn/list=";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SinaServiceProvider.class);
	
	@Override
	public List<Stock> query(String... stockNames) {
		String url = getRestfulAddress(stockNames);
		String response = requestRestfulService(url);
		return null == response ? null : parse(response);
	}
	
	private String requestRestfulService(String url) {
		Client client = new BasicClient().useConnectionPool(false);
		try {
			return client.get(url).toString();
		} catch (Exception e) {
			LOGGER.error("Error occurs while getting stock information from {}", url);
			LOGGER.error("Error details:", e);
			return null;
		} finally {
			client.shutdown();
		}
	}
	
	private List<Stock> parse(String response) {
		LOGGER.debug("Retrieved response:\r\n{}", response);
		String[] stocks = response.split(";");
		List<Stock> list = new ArrayList<Stock>(stocks.length);
		for(String stock : stocks) {
			if(StringUtils.isNotBlank(stock)) {
				list.add(new SinaStock(stock.trim()));
			}
		}
		return list;
	}

	private String getRestfulAddress(String... stockNames) {
		return new StringBuilder(RESTFUL_URL).append(StringUtils.join(stockNames, ',')).toString();
	}

	@Override
	public String getName() {
		return "新浪";
	}
}
